package com.siyoumi.modules.sys.web;

import com.siyoumi.component.XApp;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.ApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.service.vo.VoScanLogin;
import com.siyoumi.service.vo.VoLogin;
import com.siyoumi.service.vo.VoPhoneLogin;
import com.siyoumi.service.web_oauth.WebOauth;
import com.siyoumi.service.wx.WxApiService;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

//小程序接口
@RestController
@RequestMapping("/sys/app")
public class ApiSysLogin
        extends ApiController {
    @PostMapping("login")
    public XReturn login(@Validated @RequestBody VoLogin data) {
        return WxApiService.getBean().login(data);
    }

    @PostMapping("phone_login")
    @Transactional(rollbackFor = Exception.class)
    public XReturn phoneLogin(@Validated VoPhoneLogin data) {
        return WxApiService.getBean().phoneLogin(data);
    }

    /**
     * 获取登陆扫码key
     */
    @GetMapping("/login_scan_init")
    public XReturn loginScanInit() {
        String key = XStr.md5(XApp.getStrID());
        XRedis.getBean().setEx(VoScanLogin.redisKey(key), "0", 10 * 60);
        getR().setData("key", key);
        return getR();
    }

    /**
     * 登陆扫码成功，获取token
     */
    @GetMapping("/login_scan_check")
    public XReturn loginScanCheck() {
        String key = input("key");
        if (XStr.isNullOrEmpty(key)) {
            return EnumSys.MISS_VAL.getR("miss key");
        }
        String webToken = XRedis.getBean().get(VoScanLogin.redisKey(key));
        if (XStr.isNullOrEmpty(webToken)) {
            return EnumSys.TOKEN_EXPIRED.getR("key已失效");
        }
        if ("0".equals(webToken)) {
            return XReturn.getR(20050, "继续等待");
        }

        getR().setData("web_token", webToken);
        XRedis.getBean().del(key);

        return getR();
    }


    /**
     * 获取登陆数据
     */
    @GetMapping("get_token_data")
    public XReturn getTokenData() {
        InputData inputData = InputData.fromRequest();
        String webToken = inputData.input("web_token");

        if (XStr.isNullOrEmpty(webToken)) {
            return EnumSys.MISS_VAL.getR("miss web_token");
        }

        return WebOauth.getWebTokenData(webToken);
    }
}
